const http = require("http")
const url = require("url")
const fs = require("fs")
const path = require("path")
var server = http.createServer(function(req, res) {
    const pathObj = url.parse(req.url, true)
    if (pathObj.pathname === '/') {
        pathObj.pathname = './ajax请求页面.html'
    }
    if (pathObj.pathname.includes('/api')) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.writeHead(200, { "Content-Type": "application/json" });
        var otherObject = [{ item1: "item1val", item2: "item2val" }, { item1: "item1val", item2: "item2val" }]
        var json = JSON.stringify(otherObject);
        res.end(json)
    } else {

        var filePath = path.join(path.join(__dirname, '/'), pathObj.pathname)
        fs.readFile(filePath, 'binary', function(err, content) {
            if (err) {
                res.writeHead(404, 'Not Found')
                res.end('<h1>404 Not Found</h1>')
            } else {
                res.writeHead(200, 'Not Found')
                res.write(content, 'binary')
                res.end()
            }
        })
    }
})
server.listen(8080, function() {
    console.log("服务器创建成功");
})